package com.easywb.springboot.mapper.blog.service.serviceImp;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.easywb.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service("TokenService")
public class TokenService {

    private RedisTemplate redisTemplate;

    private JSONObject userInfo;

    private String token;

    @Autowired
    public TokenService(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    /**
     * 生成redis所需要的数据
     */
    public JSONObject createToken(User user) {
        String tokenString = "";
        JSONObject jSONObject = new JSONObject();
        JSONObject userMes = new JSONObject();
        try {
            tokenString = JWT.create().withAudience(String.valueOf(user.getId()))// 将 user id 保存到 token 里面
                    .sign(Algorithm.HMAC256(user.getUsername()));// 以 username 作为 token 的密钥
        } catch (Exception e) {
            throw new RuntimeException("token创建失效！");
        }
        userMes.put("id", user.getId());
        userMes.put("username", user.getUsername());
        userMes.put("profilePhotoUrl", user.getProfilePhotoUrl());
        userMes.put("nickname", user.getNickname());
        userMes.put("pas", user.getPas());
        userMes.put("loginTime", new Date().getTime());
        jSONObject.put("token", tokenString);
        jSONObject.put("user", userMes);
        return jSONObject;
    }

    /**
     * 往redis存用户信息
     */
    public JSONObject createCacheUser(JSONObject user) {
        JSONObject data = new JSONObject();
        try {
            JSONObject userIn = (JSONObject) user.get("user");
            redisTemplate.opsForHash().put("user", userIn.get("id"), user);
            data.put("type", true);
        } catch (Exception e) {
            throw new RuntimeException("token创建失效！");
        }
        return data;
    }

    /**
     * 验证token
     */
    public JSONObject volidToken(String token) {
        JSONObject data = new JSONObject();
        JSONObject userInfo = new JSONObject();
        String id = JWT.decode(token).getAudience().get(0);
        Boolean type = false;
        if (id != null) {
            userInfo = (JSONObject) redisTemplate.opsForHash().get("user", Integer.parseInt(id));
            if (userInfo == null) {
                type = false;
            } else {
                String redis_token = (String) userInfo.get("token");
                if (redis_token != null) {
                    if (token.equals(redis_token)) {
                        this.setUserInfo(redis_token);
                        this.setToken(redis_token);
                        type = true;
                    }
                }
            }

        }
        data.put("type", type);
        data.put("user", userInfo);
        return data;
    }

    ;

    /**
     * 设置用户信息
     */
    public void setUserInfo(String token) {
        String id = JWT.decode(token).getAudience().get(0);
        JSONObject user = (JSONObject) redisTemplate.opsForHash().get("user", Integer.parseInt(id));
        userInfo = (JSONObject) user.get("user");
    }

    /**
     * 获取用户信息
     */
    public User getUserInfo() {
        User user = new User();
        user.setUsername((String) userInfo.get("username"));
        user.setId((Integer) userInfo.get("id"));
        user.setPas((String) userInfo.get("pas"));
        user.setProfilePhotoUrl((String) userInfo.get("profilePhotoUrl"));
        user.setNickname((String) userInfo.get("nickname"));
        user.setNickname((String) userInfo.get("nickname"));
        return user;
    }

    /**
     * 获取token-String
     */
    public String getToken() {
        return token;
    }

    /**
     * 设置token-String
     */
    public void setToken(String t) {
        token = t;
    }
}
